<?php
/**
 * Executes queries on the database
 * 
 * Basically serving as an abstraction layer.  It would be better simply to
 * provide an interface or something more easily adaptable.
 * 
 * @package shoehorn
 */

/**
 * Shoehorn MySQL Database Class
 * 
 * MySQL database class.
 *
 * @package shoehorn
 * @subpackage classes
 */
class Shoehorn_Data_Mysql extends Shoehorn_Data
{
	
	protected $dsn;
	protected $err;
	private $dbc;
	
	function __construct($dsn, &$err)
	{
		parent::__construct($dsn, $err);
		
        //mysql/username:password,database@host
        
        $pos[1] = strpos($dsn, '/')+1;
        $pos[2] = strpos($dsn, ':')+1;
        $pos[3] = strpos($dsn, ',')+1;
        $pos[4] = strpos($dsn, '@')+1;
		
        $dsnArr= array();
		$dsnArr['user'] = substr($dsn, $pos[1], $pos[2] - $pos[1]-1);
		$dsnArr['pass'] = substr($dsn, $pos[2], $pos[3] - $pos[2]-1);
		$dsnArr['db'] = substr($dsn, $pos[3], $pos[4] - $pos[3]-1);
		$dsnArr['host'] = substr($dsn, $pos[4]);
		//print_r($dsnArr); //for debugging
		
		//now attempt to connect
		if($this->dbc = mysql_connect($dsnArr['host'], $dsnArr['user'], $dsnArr['pass'])) {
		    if(mysql_select_db($dsnArr['db'], $this->dbc)) {
		        return true;
		    } else {
		        $this->err->logError(2003, "Shoehorn_Data_MySQL::__construct", SH_E_FATAL, mysql_error($this->dbc));
		        return false;
		    }
		} else {
		        $this->err->logError(2002, "Shoehorn_Data_MySQL::__construct", SH_E_FATAL, mysql_error($this->dbc));
			return false;
		}
	}
	
	/**
	 * Execute a query
	 *
	 * @param string $query
	 * @return resource|false
	 */
	function execute($query)
	{
		$query = trim($query);
		if($result = mysql_query($query, $this->dbc)) {
		    return($result);
		} else {
	        $this->err->logError(2005, "Shoehorn_Data_MySQL::execute", SH_E_FATAL, mysql_error($this->dbc));
		    return(false);
		}
	}
	
	/**
	 * retrieve next row as an array
	 * 
	 * @param resource $resultIdentifier
	 * @return array|false
	 */
	function nextRow($resultIdentifier)
	{
	    if(($newRow = mysql_fetch_array($resultIdentifier, MYSQL_ASSOC)) !== false) {
	        return($newRow);
	    } else {
	        $this->err->logError(2006, "Shoehorn_Data_MySQL::nextRow", SH_E_SILENT, mysql_error($this->dbc));
		    return(false);
	    }
	}
	
}